package com.sangeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.domain.ResponseResult;
import com.sangeng.entity.Menu;
import com.sangeng.service.IMenuService;
import com.sangeng.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @RequestMapping("/list")
    public ResponseResult list(String menuName, String status) {
        // 可以针对菜单名进行模糊查询 也可以针对菜单的状态进行查询
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(menuName), Menu::getMenuName, menuName);
        wrapper.eq(StringUtils.hasText(status), Menu::getStatus, status);
        // 按照parentId和orderNum进行排序
        wrapper.orderByAsc(Menu::getParentId, Menu::getOrderNum);
        return ResponseResult.okResult(menuService.list(wrapper));
    }

    // 新增菜单
    @PostMapping
    public ResponseResult saveMenu(@RequestBody Menu menu) {
        menuService.save(menu);
        return ResponseResult.okResult();
    }

    // 根据id查询菜单数据
    @GetMapping("/{id}")
    public ResponseResult getMenu(@PathVariable("id") Long id) {
        return ResponseResult.okResult(menuService.getById(id));
    }

    // 修改菜单
    @PutMapping
    public ResponseResult updateMenu(@RequestBody Menu menu) {
        if (menu.getId().equals(menu.getParentId())) {
            return ResponseResult.errorResult(500, "修改菜单失败，上级菜单不能选择自己");
        }
        menuService.updateById(menu);
        return ResponseResult.okResult();
    }

    // 删除菜单
    @DeleteMapping("/{id}")
    public ResponseResult deleteMenu(@PathVariable("id") Long id) {
        // 如果要删除的菜单有子菜单则
        if (menuService.getById(id).getChildren() != null) {
            return ResponseResult.errorResult(500, "删除菜单失败，请先删除子菜单");
        }
        menuService.removeById(id);
        return ResponseResult.okResult();
    }

    @GetMapping("/treeselect")
    public ResponseResult treeselect() {
        // 获取当前用户
        return ResponseResult.okResult(menuService.selectMenuTree());
    }

    // 根绝角色id 获取菜单权限
    @GetMapping("/roleMenuTreeselect/{roleId}")
    public ResponseResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        return ResponseResult.okResult(menuService.selectMenuTreeByRoleId(roleId));
    }

}
